package com.shf.dynamodb.converter;

import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTypeConverter;
import com.shf.dynamodb.entity.CatalogItem.DimensionType;

/**
 * 自定义DimensionType转换器，转换为 DynamoDB 中的字符串（例如 8.5x11x.05）
 * @author songhaifeng
 */
public class DimensionTypeConverter implements DynamoDBTypeConverter<String,DimensionType> {

	/**
	 * 对象转为字符串
	 */
    @Override
    public String convert(DimensionType object) {
        DimensionType itemDimensions = (DimensionType)object;      
        String dimension = null;
        try {
            if (itemDimensions != null) {
                dimension = String.format("%s x %s x %s", 
                        itemDimensions.getLength(),
                        itemDimensions.getHeight(),
                        itemDimensions.getThickness());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dimension; 
    }

    /**
	 * 字符串转为对象
	 */
    @Override
    public DimensionType unconvert(String s) {
      
        DimensionType itemDimension = new DimensionType();
        try {
            if (s != null && s.length() !=0 ) {
                String[] data = s.split("x");
                itemDimension.setLength(data[0].trim());
                itemDimension.setHeight(data[1].trim());
                itemDimension.setThickness(data[2].trim());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return itemDimension;
    }
}